package lumis.portal.group.standardmembership;

import lumis.portal.PortalException;
import lumis.portal.PortalObjectAlreadyExistsException;
import lumis.portal.PortalObjectNotFoundException;
import lumis.portal.UnexpectedException;
import lumis.portal.dao.jdbc.ITransactionJdbc;
import lumis.portal.group.IGroupManager;
import lumis.util.ITransaction;

import java.util.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Standard Group membership JDBC-based DAO implementation.
 * 
 * @version $Revision: 10458 $ $Date: 2009-06-02 15:49:09 -0300 (Tue, 02 Jun 2009) $
 * @since 4.2.1
 */
class GroupMembershipDaoJdbc
{
	/**
	 * Adds in persistence information about a single membership.
	 * @param groupTypeId the group type identifier.
	 * @param groupId the group identifier.
	 * @param memberId the member identifier.
	 * @param transaction the transaction for persistence access.
	 * @since 4.2.1
	 */
	public void addMember(String groupTypeId, String groupId, String memberId, 
			ITransaction transaction) throws PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			PreparedStatement statement = connection.prepareStatement("insert into lum_GroupMember (groupId, principalId) values (?, ?) ");
			try
			{
				statement.setString(1, groupId);
				statement.setString(2, memberId);

				try
				{
					statement.executeUpdate();
				}
				catch (SQLException e)
				{
					try
					{
						Collection<String> groupsOfMember = getGroups(groupTypeId, memberId, transaction);
						for(String group: groupsOfMember)
						{
							if(groupId.equals(group))
							{
								throw new PortalObjectAlreadyExistsException("STR_RESOURCE_ALREADY_EXISTS;" + groupId, e);
							}
						}
					}
					catch (PortalObjectNotFoundException e1)
					{
						throw e;
					}
				}
			}
			finally
			{
				statement.close();
			}
		}
		catch (SQLException e)
		{
			throw new UnexpectedException(e);
		}
	}

	/**
	 * Deletes from persistence information about a single membership.
	 * @param groupId the group identifier.
	 * @param memberId the member identifier.
	 * @param transaction the transaction for persistence access.
	 * @since 4.2.1
	 */
	public boolean deleteMember(String groupId, String memberId, ITransaction transaction) throws PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			PreparedStatement statement = connection.prepareStatement("delete from lum_GroupMember where groupId = ? and principalId = ?");
			try
			{
				statement.setString(1, groupId);
				statement.setString(2, memberId);
				int count = statement.executeUpdate();
				return count > 0;
			}
			finally
			{
				statement.close();
			}
		}
		catch (SQLException e)
		{
			throw new UnexpectedException(e);
		}
	}
	
	/**
	 * Delete from persistence information about all membership in a group.
	 * @param groupId the group identifier.
	 * @param transaction the transaction for persistence access.
	 * @since 4.2.1
	 */
	public void deleteAllMembers(String groupId, ITransaction transaction) throws PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			PreparedStatement statement = connection.prepareStatement("delete from lum_GroupMember where groupId = ?");
			try
			{
				statement.setString(1, groupId);
				statement.executeUpdate();
			}
			finally
			{
				statement.close();
			}
		}
		catch (SQLException e)
		{
			throw new UnexpectedException(e);
		}
	}
	
	/**
	 * Reads from persistence information about a group's membership.
	 * @param groupId the group identifier.
	 * @param filterType what kind of members should be returned. Must be one
	 * of {@link IGroupManager#FILTER_TYPE_ONLY_GROUPS}, 
	 * {@link IGroupManager#FILTER_TYPE_ONLY_USERS} or
	 * {@link IGroupManager#FILTER_TYPE_USERS_AND_GROUPS}.
	 * @param transaction the transaction for persistence access.
	 * @return the members identifiers.
	 * @since 4.2.1
	 */
	public Collection<String> getMembers(String groupId, int filterType, ITransaction transaction) throws PortalException
	{
		try
		{
			String query;
			if(filterType == IGroupManager.FILTER_TYPE_ONLY_USERS)
				query = "select * from lum_GroupMember G inner join lum_Principal P on G.principalId = P.principalId where groupId = ? and P.type=1";
			else if(filterType == IGroupManager.FILTER_TYPE_ONLY_GROUPS)
				query = "select * from lum_GroupMember G inner join lum_Principal P on G.principalId = P.principalId where groupId = ? and P.type=2";
			else
				query = "select * from lum_GroupMember where groupId = ?";

			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();
			PreparedStatement statement = connection.prepareStatement(query);
			try
			{
				statement.setString(1, groupId);
				ResultSet resultSet = statement.executeQuery();
				try
				{
					Collection<String> members = new ArrayList<String>();
					
					while (resultSet.next())
						members.add(resultSet.getString("principalId"));
					
					return members;
				}
				finally
				{
					resultSet.close();
				}
			}
			finally
			{
				statement.close();
			}
		}
		catch (SQLException e)
		{
			throw new UnexpectedException(e);
		}
	}

	/**
	 * Reads from persistence information about a member's groups.
	 * @param memberId the member identifier.
	 * @param transaction the transaction for persistence access.
	 * @return the groups identifiers.
	 * @since 4.2.1
	 */
	public Collection<String> getGroups(String groupTypeId, String memberId, 
			ITransaction transaction) throws PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();
			PreparedStatement statement = connection.prepareStatement(
					"select gm.groupId from lum_GroupMember gm inner join " +
					"lum_Group g on gm.groupId = g.groupId " +
					"where g.groupTypeId = ? and gm.principalId = ?");
			try
			{
				statement.setString(1, groupTypeId);
				statement.setString(2, memberId);
				ResultSet resultSet = statement.executeQuery();
				try
				{
					Collection<String> groups = new ArrayList<String>();
					
					while (resultSet.next())
						groups.add(resultSet.getString("groupId"));
					
					return groups;
				}
				finally
				{
					resultSet.close();
				}
			}
			finally
			{
				statement.close();
			}
		}
		catch (SQLException e)
		{
			throw new UnexpectedException(e);
		}
	}
}
